<!--
 * @Description: 交工配合比
 * @Autor: wangwangwang
 * @Date: 2021-03-31 16:58:24
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-08-19 16:13:14
-->
<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display: flex">
        <div>
          <div class="header_right" @click="showCardNav = !showCardNav">
            <div class="title">搜索</div>
            <div>
              <transition name="from"></transition>
              <span v-show="!showCardNav">
                <i style="margin-right: 5px" class="el-icon-arrow-down"></i>
              </span>
              <transition name="to"></transition>
              <span v-show="showCardNav">
                <i style="margin-right: 5px" class="el-icon-arrow-up"></i>
              </span>
            </div>
          </div>
          <div v-show="showCardNav" class="hr"></div>
          <el-collapse-transition>
            <div v-show="showCardNav">
              <div class="search">
                <span style="display: inline-block;margin-bottom: 10px;">
                  <span style="margin-right: 12px">配合比名称</span>
                  <el-input v-model="tableParam.name" style="width: 240px" clearable placeholder="请输入" @keyup.enter.native="gettableData()" />
                </span>
                <span style="margin-left: 24px">
                  <span style="margin-right: 12px">工程名称</span>
                  <el-input v-model="tableParam.engineeringName" style="width: 240px" clearable placeholder="请输入" @keyup.enter.native="gettableData()" />
                </span>
                <el-button icon="el-icon-search" size="medium" class="bottom_all" @click="(tableParam.page = 1), gettableData()">查 询</el-button>
                <el-button size="medium" class="bottom_all_two" style="margin-left: 12px" @click="init()">重 置</el-button>
              </div>
            </div>
          </el-collapse-transition>
          <div class="hr"></div>
          <div class="card">
            <div class="card_nav">
              <div>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0" @click="addFromDate('添加'),initFormData()">
                  <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
                  添加
                </el-button>

              </div>
              <div>
                <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px">
                  <el-link :underline="false">
                    <span class="el-icon--left">
                      <i class="iconfont iconicon_button_filtrate"></i>
                    </span>
                    筛选
                  </el-link>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item, index) in table" :key="index">
                      <el-checkbox v-model="item.status">{{
                        item.label
                        }}</el-checkbox>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
            <div v-loading="tableLoading" class="card_info" :style="style">
              <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="tableData" tooltip-effect="dark">
                <template v-for="(item, index2) in table">
                  <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :width="item.width">
                    <template slot-scope="scope">
                      <span v-if="item.label == '序号'">
                        {{scope.$index+1}}
                      </span>
                      <div v-else-if="item.label=='配合比类型'">
                        <span v-if="scope.row.type == 1">通用配合比</span>
                        <span v-else-if="scope.row.type == 2">专用配合比</span>
                      </div>
                      <span v-else-if="item.label == '配合比'" @click="look2Fun(scope.row,'lookList')">
                        <span class="table_link">查看配合比</span>
                      </span>
                      <el-button v-else-if="item.label == '操作'&&ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" class="bottom_one" size="mini" @click="updateFromDate(scope.row, '修改'),look2Fun(scope.row,'formData')">
                        修改
                      </el-button>
                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
          </div>
        </div>
      </el-main>
      <div class="card_bottom">
        <div class="card_bottom_left">
          <div class="top_page_totle">总共{{ total }}条</div>
          <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" :page-sizes="[10, 20, 30, 40,50,100,200,500,1000]" layout="prev,pager,sizes,next,jumper" :total="total" @size-change="sizeChange" @current-change="gettableData()"></el-pagination>
        </div>
        <div>
          <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="gettableData">刷新</el-button>
        </div>
      </div>
    </el-container>
    <!-- 查看配合比 -->
    <el-dialog v-dialogDrag :visible.sync="addDialog2" width="680px" :close-on-click-modal="false" :before-close="resetFromDate">
      <span slot="title" class="dialog-title">查看配合比</span>
      <div class="dialoginfo">
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="lookArry" tooltip-effect="dark">
          <el-table-column label="原物料" align="center" prop="rawName"></el-table-column>
          <el-table-column label="配合比值" align="center" prop="ratioValue"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="addDialog2 = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="addDialog" width="1000px" :close-on-click-modal="false" :before-close="resetFromDate">
      <span slot="title" class="dialog-title">{{ addDialogTitle }}</span>
      <div class="dialoginfo FZYform">
        <el-form ref="reffromDate" :rules="rules" :inline="true" :model="fromDate" label-width="110px">
          <el-form-item prop="companyId" :rules="[
                    {
                      required: true,
                      message: '请选择公司',
                      trigger: 'blur',
                    },
                  ]">
            <span slot="label" style="color: #ff0000">公司</span>
            <el-select ref="selection1" v-model="fromDate.companyId" placeholder="请选择" @change="engineeringIdListFun(),$nextTick(()=>{fromDate.company = $refs.selection1.selectedLabel})">
              <el-option v-for="item in companylist" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="name">
            <span slot="label" style="color: #ff0000">配合比名称</span>
            <el-input v-model="fromDate.name" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item prop="type">
            <span slot="label" style="color: #ff0000">配合比类型</span>
            <el-select v-model="fromDate.type" placeholder="请选择">
              <el-option label="通用配合比" :value="1"></el-option>
              <el-option label="专用配合比" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="strengthGradeId">
            <span slot="label" style="color: #ff0000">强度等级</span>
            <el-select v-model="fromDate.strengthGradeId" placeholder="请选择">
              <el-option v-for="item in strengthGradeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <span slot="label">性能等级</span>
            <el-select v-model="fromDate.performanceRequest0" multiple placeholder="请选择">
              <el-option v-for="item in performanceGradeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <span slot="label">材料要求</span>
            <el-select v-model="fromDate.materialRequest0" multiple placeholder="请选择">
              <el-option v-for="item in meterialRequirementsList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <span slot="label">特殊要求</span>
            <el-select v-model="fromDate.specialRequest0" multiple placeholder="请选择">
              <el-option v-for="item in specialRequirementsList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <span slot="label">其他要求</span>
            <el-select v-model="fromDate.otherRequest0" multiple placeholder="请选择">
              <el-option v-for="item in otherRequirementsList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <span slot="label">外加剂要求</span>
            <el-select v-model="fromDate.additiveRequest0" multiple placeholder="请选择">
              <el-option v-for="item in admixtureRequirementsList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="fromDate.type*1===2" prop="engineeringId" :rules="[{
            required: fromDate.type*1===2,
            message: '请选择工程',
            trigger: 'blur',
          }]">
            <span slot="label" style="color: #ff0000">工程名称</span>
            <el-select v-model="fromDate.engineeringId" placeholder="请选择">
              <el-option v-for="(item, index) in engineeringIdList" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <div class="form-title" style="margin-bottom:10px;">配合比参数</div>
          <el-form-item prop="unitWeight">
            <span slot="label" style="color: #ff0000">容重kg/m³</span>
            <el-input v-model="fromDate.unitWeight" type="Number" placeholder="请输入" clearable @change="calculatorFun(true)"></el-input>
          </el-form-item>
          <el-form-item prop="totalPlasticMaterial">
            <span slot="label" style="color: #ff0000">胶材总量</span>
            <el-input v-model="fromDate.totalPlasticMaterial" type="Number" placeholder="请输入" clearable @change="calculatorFun(true)"></el-input>
          </el-form-item>
          <el-form-item prop="waterBinderRatio">
            <span slot="label" style="color: #ff0000">水胶比</span>
            <el-input v-model="fromDate.waterBinderRatio" type="Number" placeholder="请输入" clearable @change="calculatorFun(true)"></el-input>
          </el-form-item>
          <el-form-item prop="sandRatio">
            <span slot="label" style="color: #ff0000">砂率%</span>
            <el-input v-model="fromDate.sandRatio" type="Number" placeholder="请输入" clearable @change="calculatorFun(true)"></el-input>
          </el-form-item>
          <el-form-item prop="slump" :rules="[{required: true,message: '请输入坍落度',trigger: 'blur',}]">
            <span slot="label" style="color: #ff0000">坍落度(mm)</span>
            <el-input v-model="fromDate.slump" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item prop="temperature" :rules="[{required: true,message: '请输入选用温度',trigger: 'blur',}]">
            <span slot="label" style="color: #ff0000">选用温度(℃)</span>
            <el-input v-model="fromDate.temperature" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-form>
        <div style="padding-bottom: 10px;">
          <el-button size="mini" class="bottom_all" style="margin-left: 0;" @click="addItem()">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
            添加
          </el-button>
        </div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border :row-class-name="tableRowClassName" style="width:100%" :data="toViewList" tooltip-effect="dark" class="FZYtable">
          <el-table-column label="原物料" align="center" prop="orderNo" width="140">
            <template slot-scope="scope">
              <el-select v-model="scope.row.rawId" placeholder="请选择" style="width: 100%;" @change="changeItem(scope.row,'rawId')">
                <el-option v-for="(item, index) in rawIdArry" :key="index" :label="item.itemName" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" align="center" prop="orderNo" width="140">
            <template slot-scope="scope">
              <el-select v-model="scope.row.specificationId" placeholder="请选择" style="width: 100%;" @change="changeItem(scope.row,'specificationId')">
                <el-option v-for="(item, index) in specificationIdArry" :key="index" :label="item.itemName" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="公式参数类型" align="center" prop="orderNo" width="110">
            <template slot-scope="scope">
              <el-select v-model="scope.row.formulaParametersId" placeholder="请选择" style="width: 100%;" :disabled="$options.filters.filtFormula(scope.$index)" @change="changeItem(scope.row,'formulaParametersId',scope.$index)">
                <el-option v-for="(item, index) in formulaParametersIdArry" :key="index" :label="item.name" :value="item.id" :disabled="item.type"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="参数类型" align="center" prop="parametersType" width="90"></el-table-column>
          <el-table-column label="参量" align="center" width="135">
            <template slot-scope="scope">
              <div style="text-align: left;">
                <el-input-number v-model="scope.row.parameter" :controls="false" :precision="$options.filters.precision(scope.row)" style="width: 80px;" :disabled="scope.row.formulaParametersId==2" @change="calculatorFun()"></el-input-number>
                <span v-if="scope.row.formulaParametersId !=6"> %</span><span v-else> kg/m³</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="配合比值" align="center">
            <template slot-scope="scope">
              {{scope.row.ratioValue}} kg/m³
            </template>
          </el-table-column>
          <el-table-column label="厂家材质报告" align="center">
            <template slot-scope="scope">
              <el-upload action="/resource/resources/upload" :show-file-list="false" :before-upload="beforeUpload" :on-success="filesuccess">
                <el-link class="table_link" :underline="false" @click="scopeIndex=1,rowIndex=scope.$index">{{scope.row.materialReportPath?'修改':'上传'}}</el-link>
              </el-upload>
              <div v-if="scope.row.materialReportPath" class="upload-item-text">
                <a class="el-link" :href="'/file/' +scope.row.materialReportPath" download>
                  <span style="color:#3f8e4d;">{{scope.row.materialReport}}</span>
                  <i class="el-icon-download" style="padding:0 10px"></i>
                </a>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="合格证" align="center">
            <template slot-scope="scope">
              <el-upload action="/resource/resources/upload" :show-file-list="false" :before-upload="beforeUpload" :on-success="filesuccess">
                <el-link class="table_link" :underline="false" @click="scopeIndex=2,rowIndex=scope.$index">{{scope.row.qualificationPath?'修改':'上传'}}</el-link>
              </el-upload>
              <div v-if="scope.row.qualificationPath" class="upload-item-text">
                <a class="el-link" :href="'/file/' +scope.row.qualificationPath" download>
                  <span style="color:#3f8e4d;">{{scope.row.materialReport}}</span>
                  <i class="el-icon-download" style="padding:0 10px"></i>
                </a>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="100">
            <template slot-scope="scope">
              <el-button v-show="$options.filters.filtDel(scope.$index)" size="mini" class="bottom_two" @click="deleteItem(scope.row,scope.$index)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" @click="submitFromDate()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixin from "@/mixins/ICPSmixin.js";
import {
  queryPage, getLists, getProjectByCompanyId, getRatioDetail, saveOrUpdate
} from "@/api/smart/mix.js";
import { getDicType } from "@/api/common.js";
import { formatTreeData } from "@/utils/utils";
import { queryPage as getorganization } from "@/api/basedata/organization.js";
import { permissionsCompanyList, getFileDetails } from "@/api/common.js";
// import FileComponent from './components_data/fileComponent';
import { getToken, getUserId } from '@/utils/auth';
let loadingInstance;
import { Loading } from 'element-ui';
export default {
  // components: { FileComponent },
  mixins: [mixin],
  data() {
    return {
      upheader: {
        "access-token": getToken(),
        "user-id": getUserId(),
      },
      scopeIndex: '',//1厂家材质报告，2合格证书
      rowIndex: '',//第几行的
      materialReportFileCheck: {},//厂家材质报告校验
      qualificationFileCheck: {}, //合格证书校验
      files: [],
      companylist: [],
      organizationName: '',
      organizationIdList: [],
      /*表格增删改查及下载接口*/
      queryPage: queryPage,
      /*表格数据*/
      table: [
        { label: "序号", width: "50", prop: "", status: true },
        { label: "配合比名称", width: "auto", prop: "name", status: true },
        { label: "配合比类型", width: "auto", prop: "type", status: true },
        { label: "配合比", width: "120", prop: "", status: true },
        { label: "工程", width: "auto", prop: "engineeringName", status: true },
        { label: "操作", width: "120", prop: "", status: true },
      ],
      pagesType: 0,
      /*添加表单数据*/
      rules: {
        name: [{ required: true, message: "请输入配合比名称", trigger: "blur" }],
        type: [{ required: true, message: "请输入配合比类型", trigger: "blur" }],
        strengthGradeId: [{ required: true, message: "请选择强度等级", trigger: "blur" }],
        unitWeight: [{ required: true, message: "请输入容重", trigger: "blur" }],
        totalPlasticMaterial: [{ required: true, message: "请输入胶材总量", trigger: "blur" }],
        waterBinderRatio: [{ required: true, message: "请输入水胶比", trigger: "blur" }],
        sandRatio: [{ required: true, message: "请输入砂率", trigger: "blur" }],
      },
      fromDate: {
      },
      addDialog2: false,
      toViewList: [],
      lookArry: [],
      strengthGradeList: [],
      performanceGradeList: [],
      meterialRequirementsList: [],
      specialRequirementsList: [],
      otherRequirementsList: [],
      admixtureRequirementsList: [],
      engineeringIdList: [],
      rawIdArry: [],
      specificationIdArry: [],
      formulaParametersIdArry: [
        {
          id: '1',
          name: '水'
        },
        {
          id: '2',
          name: '水泥',
          type: true
        },
        {
          id: '3',
          name: '细骨料'
        },
        {
          id: '4',
          name: '掺合料'
        },
        {
          id: '5',
          name: '外加剂'
        },
        {
          id: '6',
          name: '纤维'
        },
        {
          id: '7',
          name: '粗骨料'
        },
      ]
    };
  },
  async created() {
    this.companylist = await permissionsCompanyList()
    /**获取组织 */
    const params = {
      page: 1,
      pageSize: 10000,
    };
    getorganization(params).then((res) => {
      if (res.code === 1001) {
        const { data } = res.data;
        this.organizationIdList = formatTreeData(
          data,
          "id",
          "parentId",
          "children",
          "parent_id"
        );
      }
    });
    getDicType({ code: "MATspec" }).then((res) => {
      this.specificationIdArry = res.data.items; //
    });
    getDicType({ code: "MATname" }).then((res) => {
      this.rawIdArry = res.data.items;
    });
    getLists().then((res) => {
      res.data.forEach((v) => {
        if (v.typeName == "强度等级") {
          this.strengthGradeList = v.list;
        } else if (v.typeName == "规范性能等级") {
          this.performanceGradeList = v.list;
        } else if (v.typeName == "材料要求") {
          this.meterialRequirementsList = v.list;
        } else if (v.typeName == "特殊要求") {
          this.specialRequirementsList = v.list;
        } else if (v.typeName == "其他要求") {
          this.otherRequirementsList = v.list;
        } else if (v.typeName == "外加剂要求") {
          this.admixtureRequirementsList = v.list;
        }
      });
    });
    this.tableParam = { ...this.tableParam, name: "", code: "" };
    this.gettableData();
    //厂家材质报告
    getFileDetails({ code: 'certificateOfApproval' }).then(res => {
      if (res.code === 1001) {
        console.log(res.data, 'certificateOfApproval')
        this.materialReportFileCheck = res.data;
      }
    })
    //合格证书
    getFileDetails({ code: 'manufacturerMaterialReport' }).then(res => {
      if (res.code === 1001) {
        console.log(res.data, 'manufacturerMaterialReport')
        this.qualificationFileCheck = res.data;
      }
    })
  },
  methods: {
    engineeringIdListFun() {
      getProjectByCompanyId({ companyId: this.fromDate.companyId }).then((res) => {
        this.engineeringIdList = res.data
      })
    },
    /**上传前的验证 */
    beforeUpload(file) {
      console.log(this.scopeIndex, this.rowIndex);
      if (this.scopeIndex == 1) {
        if (!this.materialReportFileCheck || !this.materialReportFileCheck ?.fileType) {
          this.$message.error('当前流程未配置附件，请配置后再进行上传');
          return false;
        }
        const fileType = file.name.split('.')[1];
        const isTYPE = this.materialReportFileCheck.fileType.indexOf(fileType) > -1;
        const isLtM = file.size / 1024 / 1024 < this.materialReportFileCheck.trillionSize;
        if (!isTYPE) {
          this.$message.error('图片格式只能为' + this.materialReportFileCheck.fileType);
          return false;
        }
        if (!isLtM) {
          this.$message.error(`图片大小不能超过${this.materialReportFileCheck.trillionSize}M`);
          return false;
        }
      } else if (this.scopeIndex == 2) {
        if (!this.qualificationFileCheck || !this.qualificationFileCheck ?.fileType) {
          this.$message.error('当前流程未配置附件，请配置后再进行上传');
          return false;
        }
        const fileType = file.name.split('.')[1];
        const isTYPE = this.qualificationFileCheck.fileType.indexOf(fileType) > -1;
        const isLtM = file.size / 1024 / 1024 < this.qualificationFileCheck.trillionSize;
        if (!isTYPE) {
          this.$message.error('图片格式只能为' + this.qualificationFileCheck.fileType);
          return false;
        }
        if (!isLtM) {
          this.$message.error(`图片大小不能超过${this.qualificationFileCheck.trillionSize}M`);
          return false;
        }
      }
      loadingInstance = Loading.service({ text: '上传中...' });
      return true;
    },
    /**上传成功后的赋值 */
    filesuccess(res) {
      console.log(res.data);
      if (res.code === 1001) {
        if (this.scopeIndex == 1) {
          this.toViewList[this.rowIndex].materialReport = res.data.fileName
          this.toViewList[this.rowIndex].materialReportPath = res.data.fileUrl
          loadingInstance.close();
        } else if (this.scopeIndex == 2) {
          this.toViewList[this.rowIndex].qualification = res.data.fileName
          this.toViewList[this.rowIndex].qualificationPath = res.data.fileUrl
          loadingInstance.close();

        }
      }
    },
    /**
     * @Description: 删除附件
     * @Param: 
     * @Author: wangwangwang
     */
    deleteFile(index) {
      console.log(this.files);
      this.files.splice(index, 1);
    },
    /**
     * @Description: 上传成功
     * @Param: 
     * @Author: wangwangwang
     */
    uplodeSuccess(data, index, size) {
      console.log(data.fileName);
      if (size) {
        this.toViewList[index].fileName1 = data.fileName
        console.log(this.toViewList[index].fileName1);
      } else {
        this.toViewList[index].fileName2 = data.fileName
        console.log(this.toViewList[index].fileName2);
      }
      this.files.push(data);
    },
    /*表单*/
    addItem() {
      let data = {
        type: 1,  //1新增，2修改，3删除
        rawName: "",//物料名称
        rawId: "",//物料id
        specification: "",//规格
        specificationId: "",//规格id
        formulaParameters: "",//公式参数类型
        formulaParametersId: '',  //1水、2水泥、3细骨料、4掺合料、5外加剂、6纤维
        parametersType: "",//参数类型
        parameter: 0,  //参量
        ratioValue: 0     //配合比值
      }
      this.toViewList.push(data);
    },
    deleteItem(index) {
      this.toViewList.splice(index, 1);
      this.parametersTypeFun()
      this.calculatorFun()
    },
    /**查看配合比和修改 */
    look2Fun(e, type) {
      getRatioDetail({ id: e.id }).then((res) => {
        if (type == 'lookList') {
          this.addDialog2 = true
          this.lookArry = res.data.list
        } else {
          this.fromDate = res.data
          if (this.fromDate.performanceRequest) {
            this.fromDate.performanceRequest0 = JSON.parse(this.fromDate.performanceRequest).map((v) => {
              return v.id
            });
          } else {
            this.fromDate.performanceRequest = [];
          }
          if (this.fromDate.materialRequest) {
            this.fromDate.materialRequest0 = JSON.parse(this.fromDate.materialRequest).map((v) => {
              return v.id
            });
          } else {
            this.fromDate.materialRequest = [];
          }
          if (this.fromDate.specialRequest) {
            this.fromDate.specialRequest0 = JSON.parse(this.fromDate.specialRequest).map((v) => {
              return v.id
            });
          } else {
            this.fromDate.specialRequest = [];
          }
          if (this.fromDate.otherRequest) {
            this.fromDate.otherRequest0 = JSON.parse(this.fromDate.otherRequest).map((v) => {
              return v.id
            });
          } else {
            this.fromDate.otherRequest = [];
          }
          if (this.fromDate.additiveRequest) {
            this.fromDate.additiveRequest0 = JSON.parse(this.fromDate.additiveRequest).map((v) => {
              return v.id
            });
          } else {
            this.fromDate.additiveRequest = [];
          }
          this.toViewList = JSON.parse(JSON.stringify(this.fromDate.list))
          // this.organizationName = this.fromDate.organization
          console.log(JSON.parse(JSON.stringify(this.fromDate)))
        }
      })
    },
    submitFromDate() {
      this.$refs.reffromDate.validate((valid) => {
        if (valid) {
          /**细骨料参量和 */
          let slenderPercentage = 0
          /**粗骨料参量和 */
          let thickPercentage = 0
          /**水参量和 */
          let waterPercentage = 0
          this.toViewList.forEach((v) => {
            if (v.formulaParametersId == 3) {
              slenderPercentage = slenderPercentage + (Number(v.parameter))
            }
            if (v.formulaParametersId == 7) {
              thickPercentage = thickPercentage + (Number(v.parameter))
            }
            if (v.formulaParametersId == 1) {
              waterPercentage = waterPercentage + (Number(v.parameter))
            }
          })
          if (slenderPercentage != 100 && slenderPercentage != 0) {
            this.$message({
              message: '细骨料参量和不是100%，请填写正确的参量值',
              type: 'warning'
            });
          } else if (thickPercentage != 100 && thickPercentage != 0) {
            this.$message({
              message: '粗骨料参量和不是100%，请填写正确的参量值',
              type: 'warning'
            });
          } else if (waterPercentage != 100 && waterPercentage != 0) {
            this.$message({
              message: '水参量和不是100%，请填写正确的参量值',
              type: 'warning'
            });
          } else {
            this.fromDate.strengthGrade = this.$fromatTable(
              this.strengthGradeList,
              this.fromDate.strengthGradeId,
              "id",
              "name"
            );
            this.fromDate.engineeringName = this.$fromatTable(
              this.engineeringIdList,
              this.fromDate.engineeringId,
              "id",
              "name"
            );
            //性能等级-开始数据重装
            if (this.fromDate.performanceRequest0 ?.length > 0) {
              let arr = [];
              this.fromDate.performanceRequest0.forEach((v) => {
                this.performanceGradeList.forEach((v2) => {
                  if (v == v2.id) {
                    arr.push({
                      id: v,
                      name: v2.name,
                    });
                  }
                });
              });
              this.fromDate.performanceRequest = arr;
            }
            this.fromDate.performanceRequest = JSON.stringify(this.fromDate.performanceRequest);
            //材料要求-开始数据重装
            if (this.fromDate.materialRequest0 ?.length > 0) {
              let arr = [];
              this.fromDate.materialRequest0.forEach((v) => {
                this.meterialRequirementsList.forEach((v2) => {
                  if (v == v2.id) {
                    arr.push({
                      id: v,
                      name: v2.name,
                    });
                  }
                });
              });
              this.fromDate.materialRequest = arr;
            }
            this.fromDate.materialRequest = JSON.stringify(this.fromDate.materialRequest);
            //特殊要求-开始数据重装
            if (this.fromDate.specialRequest0 ?.length > 0) {
              let arr = [];
              this.fromDate.specialRequest0.forEach((v) => {
                this.specialRequirementsList.forEach((v2) => {
                  if (v == v2.id) {
                    arr.push({
                      id: v,
                      name: v2.name,
                    });
                  }
                });
              });
              this.fromDate.specialRequest = arr;
            }
            this.fromDate.specialRequest = JSON.stringify(this.fromDate.specialRequest);
            //其他要求-开始数据重装
            if (this.fromDate.otherRequest0 ?.length > 0) {
              let arr = [];
              this.fromDate.otherRequest0.forEach((v) => {
                this.otherRequirementsList.forEach((v2) => {
                  if (v == v2.id) {
                    arr.push({
                      id: v,
                      name: v2.name,
                    });
                  }
                });
              });
              this.fromDate.otherRequest = arr;
            }
            this.fromDate.otherRequest = JSON.stringify(this.fromDate.otherRequest);
            //外加剂要求-开始数据重装
            if (this.fromDate.additiveRequest0 ?.length > 0) {
              let arr = [];
              this.fromDate.additiveRequest0.forEach((v) => {
                this.admixtureRequirementsList.forEach((v2) => {
                  if (v == v2.id) {
                    arr.push({
                      id: v,
                      name: v2.name,
                    });
                  }
                });
              });
              this.fromDate.additiveRequest = arr;
            }
            this.fromDate.additiveRequest = JSON.stringify(this.fromDate.additiveRequest);
            //列表增删改对比-------开始
            if (this.fromDate.list) {
              let update = this.toViewList.filter((res) =>
                this.fromDate.list.some((item) => res.id == item.id)
              );
              // update.forEach((res) => {
              //   res.type = 2;//修改的
              // });
              let deleteData = this.fromDate.list.filter(
                (res) => !update.some((item) => res.id == item.id)
              );
              deleteData.forEach((res) => {
                res.type = 3; //3是删除
              });
              let addData = this.toViewList.filter(
                //新增的type默认写死为 1
                (res) => !update.some((item) => res.id == item.id)
              );
              this.fromDate.list = [...update, ...deleteData, ...addData];
            } else {
              this.fromDate.list = this.toViewList
            }
            console.log(JSON.parse(JSON.stringify(this.fromDate)))
            saveOrUpdate(this.fromDate).then((res) => {
              if (res.code == 1001) {
                this.addDialog = false;
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                this.tableParam.page = 1
                this.gettableData();
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    init() {
      /*重置数据*/
      this.tableParam.name = "";
      this.tableParam.engineeringName = "";
      this.gettableData();
    },
    /**赋值name名 */
    changeItem(e, name) {
      if (name == 'rawId') {
        e.rawName = this.$fromatTable(
          this.rawIdArry,
          e.rawId,
          "id",
          "itemName"
        );
      } else if (name == 'specificationId') {
        e.specification = this.$fromatTable(
          this.specificationIdArry,
          e.specificationId,
          "id",
          "itemName"
        );
      } else if (name == 'formulaParametersId') {
        e.formulaParameters = this.$fromatTable(
          this.formulaParametersIdArry,
          e.formulaParametersId,
          "id",
          "name"
        );
        this.parametersTypeFun()
        this.calculatorFun()
      }
    },
    /** 算值配合比值,同时验证参数是否完整 */
    calculatorFun(type) {
      if (!this.fromDate.unitWeight || !this.fromDate.totalPlasticMaterial || !this.fromDate.waterBinderRatio || !this.fromDate.sandRatio) {
        if (!type) {
          this.$message({
            message: '请填写容重、胶材总量、水胶比、砂率',
            type: 'warning'
          });
        }
      } else {
        /** 所有水的配合比值和 */
        let waterAll = 0
        /** 所有水泥的配合比值和 */
        let cementAll = 0
        /** 所有掺合料的配合比值和 */
        let admixtureAll = 0
        /** 所有掺合料的参量和 */
        let admixtureParameterAll = 0
        /** 所有外加剂的配合比值和 */
        let additiveAll = 0
        /** 所有细骨料的配合比值和 */
        let slenderAll = 0
        //按调用参数顺序先算4，5，再算1，再算2，再算3，再算7【6跟谁都无关最后算】!!!!!!!!!!!!!!!
        //4掺合量和5:外加剂：胶材总量*参量
        this.toViewList.forEach((v) => {
          if (v.formulaParametersId == 4 || v.formulaParametersId == 5) {
            if (v.formulaParametersId == 5) {
              v.ratioValue = (Number(this.fromDate.totalPlasticMaterial) * (v.parameter / 100)).toFixed(2)
            } else {
              v.ratioValue = (Number(this.fromDate.totalPlasticMaterial) * (v.parameter / 100)).toFixed(0)
            }
          }
        })
        this.toViewList.forEach((v) => {
          if (v.formulaParametersId == 4) {
            admixtureAll = admixtureAll + Number(v.ratioValue)
            admixtureParameterAll = admixtureParameterAll + Number(v.parameter / 100)
          }
          if (v.formulaParametersId == 5) {
            additiveAll = additiveAll + Number(v.ratioValue)
          }
        })
        //1水：胶材总量*水胶比-（所有外加剂的配合比值和 *0.9）*水N的参量
        this.toViewList.forEach((v) => {
          if (v.formulaParametersId == 1) {
            v.ratioValue = ((Number(this.fromDate.totalPlasticMaterial) * Number(this.fromDate.waterBinderRatio)) - (additiveAll * 0.9) * (v.parameter / 100)).toFixed(0)
          }
        })
        this.toViewList.forEach((v) => {
          if (v.formulaParametersId == 1) {
            waterAll = waterAll + Number(v.ratioValue)
          }
        })
        //2水泥：胶材总量*（1-所有掺合料参量的和）
        this.toViewList.forEach((v) => {
          if (v.formulaParametersId == 2) {
            v.ratioValue = (Number(this.fromDate.totalPlasticMaterial) * (1 - admixtureParameterAll)).toFixed(0)
          }
        })
        this.toViewList.forEach((v) => {
          if (v.formulaParametersId == 2) {
            cementAll = cementAll + Number(v.ratioValue)
          }
        })
        //3细骨料N：【容重-所有水的配合比值之和-所有水泥配合比值之和-所有掺合料的配合比值之和-所有外加剂的配合比值之和】*砂率*细骨料N的参量
        this.toViewList.forEach((v) => {
          if (v.formulaParametersId == 3) {
            v.ratioValue = ((Number(this.fromDate.unitWeight) - waterAll - cementAll - admixtureAll - additiveAll) * (Number(this.fromDate.sandRatio) / 100) * (v.parameter / 100)).toFixed(0)
          }
        })
        this.toViewList.forEach((v) => {
          if (v.formulaParametersId == 3) {
            slenderAll = slenderAll + Number(v.ratioValue)
          }
        })
        //6纤维：配合比值同参量值
        this.toViewList.forEach((v) => {
          if (v.formulaParametersId == 6) {
            v.ratioValue = v.parameter
          }
        })
        //7粗骨料N：[（所有细骨料的配合比值之和/砂率）-所有细骨料的配合比值之和]*粗骨料N参量
        this.toViewList.forEach((v) => {
          if (v.formulaParametersId == 7) {
            v.ratioValue = ((slenderAll / (Number(this.fromDate.sandRatio) / 100) - slenderAll) * (v.parameter / 100)).toFixed(0)
          }
        })
      }
    },
    /**前4个不能操作的改色 */
    tableRowClassName({ rowIndex }) {
      if (rowIndex < 4) {
        return 'ccc';
      }
    },
    /** 添加时初始列表 */
    initFormData() {
      this.toViewList = []
      function data(a, b, c, d) {
        this.type = 1  //1新增，2修改，3删除
        this.rawName = ""//物料名称
        this.rawId = ""//物料id
        this.specification = ""//规格
        this.specificationId = ""//规格id
        this.ratioValue = 0 //配合比值
        this.list = []
        this.formulaParameters = a//公式参数类型
        this.formulaParametersId = b  //1水、2水泥、3细骨料、4掺合料、5外加剂、6纤维
        this.parametersType = c//参数类型
        this.parameter = d  //参量

      }
      this.toViewList.push(new data('水', '1', "水", 100))
      this.toViewList.push(new data('水泥', '2', "水泥", 100))
      this.toViewList.push(new data('细骨料', '3', "细骨料", 100))
      this.toViewList.push(new data('外加剂', '5', "外加剂", 0))
    },
    /** 参数类型多个时追加拼接数字 */
    parametersTypeFun() {
      /** 公式参数类型：水的数量 */
      let waterSize = 0
      /** 公式参数类型：细骨料的数量 */
      let slenderSize = 0
      /** 公式参数类型：掺合料的数量 */
      let admixtureSize = 0
      /** 公式参数类型：外加剂的数量 */
      let additive = 0
      /** 公式参数类型：纤维的数量 */
      let fiberSize = 0
      /** 公式参数类型：粗骨料的数量 */
      let thickSize = 0
      this.toViewList.forEach((v) => {
        if (v.formulaParametersId == 1) {
          waterSize = waterSize + 1
        } else if (v.formulaParametersId == 3) {
          slenderSize = slenderSize + 1
        } else if (v.formulaParametersId == 4) {
          admixtureSize = admixtureSize + 1
        } else if (v.formulaParametersId == 5) {
          additive = additive + 1
        } else if (v.formulaParametersId == 6) {
          fiberSize = fiberSize + 1
        } else if (v.formulaParametersId == 7) {
          thickSize = thickSize + 1
        }
      })
      /** 拼接的数字 */
      let sizeText1 = 0, sizeText3 = 0, sizeText4 = 0, sizeText5 = 0, sizeText6 = 0, sizeText7 = 0;
      this.toViewList.forEach((v) => {
        if (v.formulaParametersId == 1) {
          if (waterSize > 1) {
            sizeText1 = sizeText1 + 1
            v.parametersType = v.formulaParameters + String(sizeText1)
          } else {
            v.parametersType = v.formulaParameters
          }
        } else if (v.formulaParametersId == 3) {
          if (slenderSize > 1) {
            sizeText3 = sizeText3 + 1
            v.parametersType = v.formulaParameters + String(sizeText3)
          } else {
            v.parametersType = v.formulaParameters
          }
        } else if (v.formulaParametersId == 4) {
          if (admixtureSize > 1) {
            sizeText4 = sizeText4 + 1
            v.parametersType = v.formulaParameters + String(sizeText4)
          } else {
            v.parametersType = v.formulaParameters
          }
        } else if (v.formulaParametersId == 5) {
          if (additive > 1) {
            sizeText5 = sizeText5 + 1
            v.parametersType = v.formulaParameters + String(sizeText5)
          } else {
            v.parametersType = v.formulaParameters
          }
        } else if (v.formulaParametersId == 6) {
          if (fiberSize > 1) {
            sizeText6 = sizeText6 + 1
            v.parametersType = v.formulaParameters + String(sizeText6)
          } else {
            v.parametersType = v.formulaParameters
          }
        } else if (v.formulaParametersId == 7) {
          if (thickSize > 1) {
            sizeText7 = sizeText7 + 1
            v.parametersType = v.formulaParameters + String(sizeText7)
          } else {
            v.parametersType = v.formulaParameters
          }
        }
      })
    },
    handleAvatarSuccess(res, file) {
      console.log(res, file);
    },
    sizeChange(value) {
      this.tableParam.pageSize = value;
      this.gettableData();
    },
  },
  filters: {
    filtFormula(index) {
      if (index > 3) {
        return false
      } else {
        return true
      }
    },
    precision(e) {
      if (e.formulaParametersId == 4) {
        return 1
      } else if (e.formulaParametersId == 5) {
        return 2
      } else {
        return 0
      }
    },
    filtDel(index) {
      if (index > 3) {
        return true
      } else {
        return false
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.el-input,
.el-select {
  width: 240px;
}
.table_link {
  margin: 0 10px;
  color: $bg_color;
  cursor: pointer;
}

.table_link:hover {
  opacity: 0.8;
}
.FZYform {
  .el-form-item {
    width: 50%;
    margin-right: 0;
  }
}
</style>
<style lang="scss">
.FZYtable {
  .ccc {
    background: #fafafa;
  }
}
</style>
